pipeline {
    agent any

    // parameters {
    // #     gitParameter branch: '', branchFilter: 'origin/(.*)', defaultValue: 'master', description: '代码分支', name: 'gitlab_branch', quickFilterEnabled: false, selectedValue: 'DEFAULT', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH'
    // # }
    // 动态显示分支下拉选项
    parameters {
        gitParameter(
            branch: '',
            branchFilter: 'origin/(.*)',
            defaultValue: 'master',
            description: '代码分支',
            name: 'gitlab_branch',
            quickFilterEnabled: false,
            selectedValue: 'DEFAULT',
            sortMode: 'NONE',
            tagFilter: '*',
            type: 'PT_BRANCH'
        )
    }

    // 定义环境变量
    environment {
        APP_NAME = "my-node-app"
        // 替换为实际的 Docker 镜像仓库地址
        REGISTRY = "your-real-docker-registry-url"
        DOCKER_IMAGE = "${REGISTRY}/${APP_NAME}"
        PROJECT_DIR = "${WORKSPACE}/MySimpleHttpServer"
        JAR_FILE = "MySimpleHttpServer-1.0-SNAPSHOT.jar"
        APP_DIR = "/usr/local/app/"
    }

    stages {
        // 清理工作区
        stage('Clean') {
            steps {
                script {
                    sh "rm -rf ${WORKSPACE} && mkdir -p ${WORKSPACE}"
                }
            }
        }

        // 拉取代码阶段
        stage('Pull') {
            steps {
                script {
                    git url: 'https://gitee.com/linux-lxf/java.git', branch: "${params.gitlab_branch}"
                }
            }
        }

        // 打包项目阶段
        stage('Package') {
            steps {
                script {
                    def packageCmd = "cd ${PROJECT_DIR} && mvn clean package"
                    try {
                        sh packageCmd
                    } catch (Exception e) {
                        echo "打包项目时出现错误: ${e.message}"
                        currentBuild.result = 'FAILURE'
                        error("打包项目失败")
                    }
                }
            }
        }

        // 部署阶段
        stage('Deploy') {
            steps {
                script {
                    try {
                        // 创建应用目录
                        sh "sudo mkdir -p ${APP_DIR}"
                        // 复制 JAR 文件
                        sh "sudo cp ${PROJECT_DIR}/target/${JAR_FILE} ${APP_DIR}"
                        // 后台运行应用(实际情况需要以脚本的形式运行)
                        sh "nohup java -jar ${APP_DIR}${JAR_FILE} > /dev/null 2>&1 &"
                    } catch (Exception e) {
                        echo "部署应用时出现错误: ${e.message}"
                        currentBuild.result = 'FAILURE'
                        error("部署应用失败")
                    }
                }
            }
        }
    }

    // 后置操作
    post {
        success {
            echo 'Pipeline completed successfully!'
        }
        failure {
            echo 'Pipeline failed!'
        }
    }
}